<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]>      <html class="no-js"> <!--<![endif]-->
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
  </head>
  <body>
    <canvas id="can1" width="500" height="500" style="border: 1px solid blue;">
       
    </canvas>
    
    <script >
      var ctx =document.getElementById("can1").getContext("2d");
          
      function checkBorder(ball){
         

        if(ball.direction == "up")    ball.y-=5;
        if(ball.direction == "down")  ball.y+=5;
        if(ball.direction == "left")  ball.x-=5;
        if(ball.direction == "right") ball.x+=5;
         // 画布范围
         let {x ,y ,r, direction} = ball;  // x, y , 为圆心位置， r 为圆的半径
         if(x < r){
          ball.x= r
         }else if( x >  500 - r){
          ball.x = 500 - r
        }else if(y < r){
          ball.y = r
         }else if(y> 500 -r){
          ball.y  = 500-r
         }
          
         
        
      }
      
     function drawCircle(ball){
      ctx.clearRect(0,0, 500,500);
      ctx.beginPath()
      ctx.arc(ball.x,ball.y, ball.r, 0, 360*Math.PI/180, true)
      ctx.closePath()
      ctx.strokeStyle= "green"
      ctx.stroke();
     }
     // es6 课可以用class 语法糖
     function Ball(x = 10,y=10,r=5 ,direction="left"){
       r = Math.min(x,y,r);
       this.x = x;
       this.y = y;
       this.r = r;
       this.direction = direction;
     }
     Ball.prototype.init = function(){
      drawCircle(this);
     }

     var ball = new Ball();// 记录小求的一些信息
     ball.init()
     
     
     document.addEventListener("keydown",function(e){
       if( e.keyCode ==  38) ball.direction = "up";
       if( e.keyCode ==  37) ball.direction = "left";
       if( e.keyCode ==  39) ball.direction = "right";
       if( e.keyCode ==  40) ball.direction = "down";
          // 绘画
          checkBorder(ball); 
          drawCircle(ball)
      
     });

    


    </script>
  </body>
</html>